#!/usr/bin/python3
# ******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# ******************************************************************************/

import os

import yaml

current_path = os.path.abspath(os.path.dirname(__file__))
sig_url = "https://gitee.com/openeuler/community/blob/master/sig/sigs.yaml"
local_yaml = os.path.join(current_path, 'sig.yaml')
pkg_list = os.path.join(current_path, 'pkg_list.txt')
result_file = os.path.join(current_path, 'result.txt')


def parse_yaml():
    """
    解析sig组的yaml内容，返回字典
    :return:
    """
    with open(local_yaml, 'r') as file:
        sigs_dict = yaml.load(file, Loader=yaml.Loader)

    return sigs_dict


def find_sig():
    """
    查找pkg_list.txt中rpm包所在的sig组，生成结果写入result.txt
    :return:
    """
    sigs_dict = parse_yaml()
    sig_rpm_list = sigs_dict.get('sigs')
    rpm_sig_dict = dict()
    for sig_rpm in sig_rpm_list:
        sig_name = sig_rpm.get('name')
        rpm_list = sig_rpm.get('repositories')
        for rpm in rpm_list:
            rpm_name = rpm.split('/')[-1]
            rpm_sig_dict[rpm_name] = sig_name

    with open(pkg_list, 'r') as file:
        search_rpm_list = file.readlines()

    with open(result_file, 'w') as file:
        for search_rpm in search_rpm_list:
            search_rpm = search_rpm.strip()
            result_content = f"{search_rpm} : {rpm_sig_dict.get(search_rpm)}"
            file.write(result_content+'\n')


if __name__ == '__main__':
    parse_yaml()
    find_sig()

